package com.yanyu.space.common.cloud.feign;

import com.yanyu.space.common.core.exception.ServiceException;
import com.yanyu.space.common.core.bean.web.RCode;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @author yanyu
 */
@Slf4j
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        String msg = null;
        try {
            msg = Util.toString(response.body().asReader());
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("feignErrorDecoder error:[{}]", msg);
        // 抛出自定义的业务异常
        if (msg.contains("Load balancer does not contain an instance for the service")) {
            return new ServiceException(RCode.SERVICE_UNAVAILABLE);
        }
        return new ServiceException();
    }
}
